import {createReducer} from 'redux-act';
import {createAction1, createAction2} from '../util';
import {bed, up} from '../util/bed';
import * as ajax from '../util/ajax';
import decode from 'jwt-decode';
import {
    LOGIN,
    setToken,
    removeToken
} from '../login';
import u from 'updeep';

let _loginTo;

export function setLoginTo(uri) {
    _loginTo = uri;
}

const name = 'app';
//创建执行ajax和reducer的action
const [
    login,
    relogin,
    cfg,
    checkpwd,
    changepwd
] = [
    `${name}_login`,
    `${name}_relogin`,
    `${name}_cfg`,
    `${name}_checkpwd`,
    `${name}_changepwd`
].map(createAction2);
//创建只执行reducer的action
const [
    logout
] = [
    `${name}_logout`
].map(createAction1);

export const actions = {
    login: (data) => bed(ajax.post(LOGIN, data), login,
        {
            login: data,
            transition: {
                success: () => ({pathname: _loginTo})
            }
        }
    ),
    relogin,
    logout: () => logout({transition: () => ({pathname: LOGIN})}),
    cfg,
    checkpwd: (data) => bed(ajax.post(`/user/checkpwd`, data), checkpwd,
        {
            //transition: () => ({pathname: LOGIN})
        }
    ),
    changepwd: (data) => bed(ajax.post(`/user/changepwd`, data), changepwd,
        {
            //transition: () => ({pathname: LOGIN})
        }
    )
};
export default createReducer({
    [login]: (state, payload) => {
        const {data: token} = payload;
        if (token) {
            setToken(token);
            payload.data = decode(token);
        }
        //payload返回的数据更新到state上
        return up(state, payload, 'user');
    },
    [relogin]: (state, user) => u({user}, state),
    [logout]: (state) => {
        removeToken();
        return u({
            user: null
        }, state);
    },
    [cfg]: (state, data) => u({cfg: {...data}}, state),
    [checkpwd]: (state, payload) => {
        const success = payload.data;
        //payload返回的数据更新到state上
        return up(state, success, 'checkpwd');
    },
    [changepwd]: (state, payload, {data, done}) => {
        let result = up(state, payload);
        if (done) {
            //TODO:需要重新登录修改授权和盐值
            result = u({app: {user: data}}, result);
        }
        return result;
    }
}, {});
